<template>
    <DraggingCanvas :componentName="`${componentName}.dragging-canvas`" :slotNames="slotNames"
        v-if="chartOptionsLoaded">
        <template v-slot:[slotName]="{ layout }" v-for="slotName in slotNames">
            <EChartsComponent :layout="layout" :ref="createEchartsComponentRefSetter(slotName)"
                @update:chart-style-option="onUpdateChartStyleOption(slotName, $event)"></EChartsComponent>
        </template>
    </DraggingCanvas>
</template>

<script lang="ts" setup>
import { ref, onMounted, defineProps, nextTick, onBeforeMount, defineExpose } from "vue"
import DraggingCanvas from '../base/dragging-container/DraggingCanvas.vue';
import EChartsComponent from "./EChartsComponent.vue";
import { DataVisualizationRequests } from "./data_visualization_large_screen"
import { EChartsCoreOption, EChartsOption } from "echarts";

const props = defineProps({
    componentName: {
        type: String,
        required: true
    }
})
let echartsComponentRefs = ref<{ [key: string]: InstanceType<typeof EChartsComponent> }>({});
const requests = ref<DataVisualizationRequests>(new DataVisualizationRequests(props.componentName));
const slotNames = ref<string[]>([])
let chartsOptions: { [key: string]: EChartsOption } = {}
let chartStyleOptions: { [key: string]: EChartsOption } = {}
const chartOptionsLoaded = ref(false) // 是否已经初次加载了图表配置
const createEchartsComponentRefSetter = (componentName: string) => {
    return (component: any) => {
        if (component) {
            echartsComponentRefs.value[componentName] = component;
        }
    };
}
const renderLargeScreen = () => {
    requests.value.getAllChartOptions().then(async (res) => {
        chartStyleOptions = await requests.value.getAllChartStyleOptions()
        chartsOptions = res
        slotNames.value = []
        for (const key in res) {
            slotNames.value.push(key)
        }
        chartOptionsLoaded.value = true // 初次加载完成后，才开始渲染各个图
        await nextTick()
        // 此时已经创建了各个图组件，但还没有渲染。因此挨个setoption
        for (const componentName in echartsComponentRefs.value) {
            echartsComponentRefs.value[componentName].setOption(chartsOptions[componentName])
            if (chartStyleOptions[componentName]) {
                console.log("set style options", chartStyleOptions[componentName])
                echartsComponentRefs.value[componentName].setStyleOption(chartStyleOptions[componentName])
            }
        }

    })
}
onBeforeMount(() => { renderLargeScreen() })

const onUpdateChartStyleOption = (chartName: string, option: EChartsOption) => {
    requests.value.saveChartStyleConfig(chartName, option).then(() => {
        console.log("saved chart style config", chartName, option)
    })
}


defineExpose({ renderLargeScreen })
</script>